import { Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
import { Style, Fill, Stroke } from "ol/style";
import Overlay from "ol/Overlay";
import GeoJSON from "ol/format/GeoJSON";
import * as geojsonData from "../data/shangcheng.json";
import { hangzhou } from "@/views/layer-management/common/hangzhouAll";

const styleFunction = (feature) => {
  if (!feature) {
    console.error("Feature is undefined");
    return; // 如果 feature 为 undefined，直接返回空样式
  }

  const density = feature.get("density");

  let fillColor;
  if (density > 1000) {
    fillColor = "rgba(255, 0, 0, 0.6)";
  } else if (density >= 500) {
    fillColor = "rgba(255, 165, 0, 0.6)";
  } else {
    fillColor = "rgba(0, 255, 0, 0.6)";
  }

  return new Style({
    fill: new Fill({
      color: fillColor,
    }),
    stroke: new Stroke({
      color: "#000",
      width: 1,
    }),
  });
};

// 加载 GeoJSON 数据
export const vectorSource = new VectorSource({
  features: new GeoJSON().readFeatures(geojsonData, {
    dataProjection: "EPSG:4326",
    featureProjection: "EPSG:4326", // 设置投影
  }),
});

// 创建矢量图层并应用样式函数
export const densityLayer = new VectorLayer({
  source: vectorSource,
  style: styleFunction,
});

// 创建提示框（tip）
export const addTipForShangcheng = (map, vectorSource) => {
  const minZoom = 9; // 设置提示框显示的最小缩放级别

  // 创建提示框的 DOM 元素
  const tipElement = document.createElement("div");
  tipElement.className = "tip-overlay";
  tipElement.innerHTML = `
    <div class="tip-content">
      <div class="tip-header">上城区</div>
      <div class="tip-body">人口密度极高</div>
      <button class="close-tip">×</button> 
    </div>`;

  // 添加炫酷的样式
  const style = document.createElement("style");
  style.innerHTML = `
    .tip-overlay {
      position: relative;
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      padding: 10px 15px;
      border-radius: 12px;
      box-shadow: 0 10px 15px rgba(0, 0, 0, 0.3);
      color: white;
      font-family: Arial, sans-serif;
      font-size: 14px;
      text-align: center;
      transform: translate(-50%, -100%);
      opacity: 0; /* 初始状态为不可见 */
      pointer-events: none; /* 确保提示框不会影响鼠标事件 */
      transition: opacity 0.3s ease-in-out;
    }
    .tip-overlay.show {
      opacity: 1; /* 显示提示框时的透明度 */
      pointer-events: auto; /* 显示时允许与提示框交互 */
    }
      .close-tip {
      position: absolute;
      top: 5px;
      right: 5px;
      background: none;
      border: none;
      color: white;
      font-size: 18px;
      cursor: pointer;
      font-weight: bold;
    }
    .close-tip:hover {
      color: #ff4d4d;
    }
  `;
  document.head.appendChild(style);

  // 创建 Overlay，并添加到地图
  const tipOverlay = new Overlay({
    element: tipElement,
    positioning: "bottom-center",
    stopEvent: false,
  });
  map.addOverlay(tipOverlay);

  // 获取上城区的中心点
  const shangchengFeature = vectorSource.getFeatures().find((feature) => {
    return feature.get("name") === "上城区"; // 这里假设“上城区”是你的 GeoJSON 中的一个属性值
  });

  if (shangchengFeature) {
    let center;

    // 检查几何类型并根据类型计算中心点
    const geometry = shangchengFeature.getGeometry();
    if (geometry.getType() === "Point") {
      center = geometry.getCoordinates(); // 如果是点，直接获取坐标
    } else if (geometry.getType() === "Polygon" || geometry.getType() === "MultiPolygon") {
      const extent = geometry.getExtent(); // 如果是多边形或多边形集，使用边界框
      center = [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];
    }

    tipOverlay.setPosition(center); // 设置 Overlay 的位置
  }

  // 根据缩放级别控制提示框显示与隐藏
  // map.getView().on("change:resolution", () => {
  //   const zoom = map.getView().getZoom();
  //   if (zoom >= minZoom) {
  //     tipElement.classList.add("show"); // 显示提示框
  //   } else {
  //     tipElement.classList.remove("show"); // 隐藏提示框
  //   }
  // });
  // 添加点击事件监听器
  map.on("singleclick", (event) => {
    // 检查当前缩放级别是否满足条件
    const zoom = map.getView().getZoom();
    if (zoom < minZoom) {
      tipElement.classList.remove("show");
      return;
    }

    // 判断点击的要素
    map.forEachFeatureAtPixel(event.pixel, (feature) => {
      if (feature.get("name") === "上城区") {
        const geometry = feature.getGeometry();
        let center;

        // 检查几何类型并计算中心点
        if (geometry.getType() === "Point") {
          center = geometry.getCoordinates();
        } else if (geometry.getType() === "Polygon" || geometry.getType() === "MultiPolygon") {
          const extent = geometry.getExtent();
          center = [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];
        }

        // 设置提示框位置并显示
        tipOverlay.setPosition(center);
        tipElement.classList.add("show");
      }
    });
  });

  // 添加关闭按钮的点击事件
  const closeButton = tipElement.querySelector(".close-tip");
  closeButton.addEventListener("click", () => {
    tipElement.classList.remove("show"); // 点击关闭按钮时隐藏提示框
  });
};
